<template>
  <div id="shuziren">
    <div class="all-title">数字教师资产库</div>
    <div class="all-box">
      <div class="back-btn" @click="goBack()">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        <span>返回</span>
      </div>
      <div class="shuziren-name">
        数字人名称：
        <el-input
          v-model="shuzirenName"
          style="width: 1000px"
          placeholder="请输入名称"
        />
      </div>
      <div class="upload-box">
        <!-- 上传图片 -->
        <div style="align-items: flex-start">
          <div class="upload-title">上传照片：</div>
          <div class="upload-area">
            <el-upload
              ref="uploadRef"
              v-model:file-list="imgFileList"
              name="file"
              class="upload-demo"
              action="/tes/digital-human/upload"
              :before-upload="beforeUpload_img"
              :on-change="handleChange_img"
              :on-success="handleSuccess_img"
              :on-error="handleError_img"
              :show-file-list="false"
            >
              <el-button type="primary" color="#0070ff">上传照片</el-button>
              <template #tip>
                <div
                  class="el-upload__tip"
                  style="font-size: 14px; color: #929eb4"
                >
                  请上传1:1比例的正脸半身照，正面朝向，清晰露出面部与手臂，背景纯色色值为：#f3f5fa，格式支持JPG、PNG
                </div>
              </template>
            </el-upload>
            <div class="upload-img" v-if="imgFileList.length > 0">
              <img :src="imgFileList[imgFileList.length - 1]?.url" alt="" />
            </div>
          </div>
        </div>
        <!-- 选择角色 -->
        <div :style="{ marginTop: imgFileList.length > 0 ? '0px' : '30px' }">
          <div class="upload-title">选择角色：</div>
          <div class="juese-item">
            <div class="man-item">
              <span
                v-for="(item, index) in manAudioList"
                :key="index"
                :ref="item.ref"
                @click="changeRole(item.value, index, item.sex)"
                :class="{ active: activeManIndex == index }"
              >
                {{ item.name }}
                <el-tooltip content="点击试听" placement="top">
                  <el-icon @click="playRoleAudio(item.name)"
                    ><Headset
                  /></el-icon>
                </el-tooltip>
              </span>
            </div>
            <div class="woman-item">
              <span
                v-for="(item, index) in womanAudioList"
                :key="index"
                :ref="item.ref"
                @click="changeRole(item.value, index, item.sex)"
                :class="{ active: activeWomanIndex == index }"
              >
                {{ item.name }}
                <el-tooltip content="点击试听" placement="top">
                  <el-icon @click="playRoleAudio(item.name)"
                    ><Headset
                  /></el-icon>
                </el-tooltip>
              </span>
            </div>
          </div>
        </div>
        <!-- 选择音色 -->
        <!-- <div style="margin-top: 20px">
          <div class="upload-title">选择音色：</div>
          <div class="yinse-item">
            <span
              >高兴<el-tooltip content="点击试听" placement="top">
                <el-icon><Headset /></el-icon>
              </el-tooltip>
            </span>
            <span
              >悲伤<el-tooltip content="点击试听" placement="top">
                <el-icon><Headset /></el-icon>
              </el-tooltip>
            </span>
          </div>
        </div> -->
      </div>
      <div class="bottom-btn">
        <el-button type="primary" color="#0070ff" @click="saveFn()"
          >保存</el-button
        >
        <el-button plain>取消</el-button>
      </div>
    </div>

    <!-- 试听播放 -->
    <audio
      ref="audio_man1"
      :src="manAudio1"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_man2"
      :src="manAudio2"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_man3"
      :src="manAudio3"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_man4"
      :src="manAudio4"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_woman1"
      :src="womanAudio1"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_woman2"
      :src="womanAudio2"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_woman3"
      :src="womanAudio3"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
    <audio
      ref="audio_woman4"
      :src="womanAudio4"
      controls
      style="display: none"
      @error="handleAudioError"
    ></audio>
  </div>
</template>
<script>
import manAudio1 from "@/assets/audio/m1.mp3";
import manAudio2 from "@/assets/audio/m2.mp3";
import manAudio3 from "@/assets/audio/m3.mp3";
import manAudio4 from "@/assets/audio/m4.mp3";
import womanAudio1 from "@/assets/audio/f1.mp3";
import womanAudio2 from "@/assets/audio/f2.mp3";
import womanAudio3 from "@/assets/audio/f3.mp3";
import womanAudio4 from "@/assets/audio/f4.mp3";

export default {
  data() {
    return {
      editId: "",
      shuzirenName: "",
      activeRole: "",
      activeManIndex: -1, // 当前选中的男声索引
      activeWomanIndex: -1, // 当前选中的女声索引
      imgFileList: [],
      fileName: "",
      manAudioList: [
        {
          name: "男声1",
          audio: manAudio1,
          ref: "audio_man1",
          value: "m1",
          sex: 1,
        },
        {
          name: "男声2",
          audio: manAudio2,
          ref: "audio_man2",
          value: "m2",
          sex: 1,
        },
        {
          name: "男声3",
          audio: manAudio3,
          ref: "audio_man3",
          value: "m3",
          sex: 1,
        },
        {
          name: "童声1",
          audio: manAudio4,
          ref: "audio_man4",
          value: "m4",
          sex: 1,
        },
      ],
      womanAudioList: [
        {
          name: "女声1",
          audio: womanAudio1,
          ref: "audio_woman1",
          value: "f1",
          sex: 0,
        },
        {
          name: "女声2",
          audio: womanAudio2,
          ref: "audio_woman2",
          value: "f2",
          sex: 0,
        },
        {
          name: "女声3",
          audio: womanAudio3,
          ref: "audio_woman3",
          value: "f3",
          sex: 0,
        },
        {
          name: "女声4",
          audio: womanAudio4,
          ref: "audio_woman4",
          value: "f4",
          sex: 0,
        },
      ],
      picToken: "", // 图片token
      manAudio1,
      manAudio2,
      manAudio3,
      manAudio4,
      womanAudio1,
      womanAudio2,
      womanAudio3,
      womanAudio4,
    };
  },
  created() {
    this.editId = this.$route.query.id;
    this.getShuzirenInfo();
  },
  methods: {
    // 获取数字人信息(编辑)
    getShuzirenInfo() {
      if (!this.editId) return;
      this.$axios
        .get(`/tes/digital-human/get?id=${this.editId}`)
        .then((res) => {
          this.shuzirenName = res.data.name;
          this.activeRole = res.data.soundType;
          this.imgFileList = [{ url: res.data.picUrl }];
          this.picToken = "";
          this.manAudioList.forEach((item, index) => {
            if (item.value == res.data.soundType) {
              this.activeManIndex = index;
            }
          });
          this.womanAudioList.forEach((item, index) => {
            if (item.value == res.data.soundType) {
              this.activeWomanIndex = index;
            }
          });
        });
    },
    // 上传图片
    beforeUpload_img(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error("图片大小不能超过 1MB!");
        return false;
      }

      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      if (!isJPG && !isPNG) {
        this.$message.error("图片格式只能是 JPG 或 PNG!");
        return false;
      }

      return true;
    },
    handleChange_img(file, fileList) {
      // 将文件转换为URL用于预览
      if (file.raw) {
        this.fileName = file.raw.name;
        const reader = new FileReader();
        reader.onload = (e) => {
          // 为文件对象添加预览URL
          file.url = e.target.result;
          this.$forceUpdate(); // 强制更新视图
        };
        reader.readAsDataURL(file.raw);
      }
      this.imgFileList = fileList;
    },
    handleSuccess_img(response, file, fileList) {
      this.picToken = response.data;
      this.imgFileList = fileList;
    },
    handleError_img(error, file, fileList) {
      console.log(error, file, fileList);
    },

    // 切换角色
    changeRole(value, index, sex) {
      if (sex == 1) {
        this.activeWomanIndex = -1;
        this.activeManIndex = index;
      } else {
        this.activeManIndex = -1;
        this.activeWomanIndex = index;
      }

      this.activeRole = value;
    },

    // 试听播放
    playRoleAudio(type) {
      // 暂停所有正在播放的音频
      const allAudioRefs1 = this.manAudioList.map((item) => item.ref);
      const allAudioRefs2 = this.womanAudioList.map((item) => item.ref);
      const allAudioRefs = [...allAudioRefs1, ...allAudioRefs2];
      allAudioRefs.forEach((refName) => {
        const audioElement = this.$refs[refName];
        if (audioElement && !audioElement.paused) {
          audioElement.pause();
          audioElement.currentTime = 0;
        }
      });
      // 查找对应的音频ref名称
      let refName = "";
      const allAudioList = [...this.manAudioList, ...this.womanAudioList];
      const audioItem = allAudioList.find((item) => item.name === type);

      if (audioItem) {
        refName = audioItem.ref;
        const audioElement = this.$refs[refName];
        if (audioElement) {
          audioElement.load();
          audioElement.play().catch((error) => {
            console.error("音频播放失败:", error);
          });
        }
      }
    },

    // 添加/修改保存
    saveFn() {
      if (!this.shuzirenName) {
        this.$message.error("请输入数字人名称");
        return;
      }
      if (!this.activeRole) {
        this.$message.error("请选择角色");
        return;
      }
      if (this.imgFileList.length == 0 || this.imgFileList[0].url == "") {
        this.$message.error("请上传照片");
        return;
      }
      let data = {};
      if (!this.editId) {
        data = {
          name: this.shuzirenName,
          soundType: this.activeRole,
          picToken: this.picToken,
          type: "1",
        };
      } else {
        let picToken = this.fileName ? this.picToken : "";
        data = {
          id: this.editId,
          name: this.shuzirenName,
          soundType: this.activeRole,
          picToken: picToken,
          type: "1",
        };
      }
      this.$axios.post(`/tes/digital-human/save`, data).then((res) => {
        this.$message.success("保存成功");
        this.$router.push({
          path: "/shuziren",
        });
      });
    },

    // 返回
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
#shuziren {
  .all-box {
    position: relative;
    padding: 80px 68px 60px;
    box-sizing: border-box;
    .shuziren-name {
      display: flex;
      align-items: center;
      color: #333333;
      .add-left {
        .add-title {
          font-weight: bold;
          font-size: 24px;
          color: #ffffff;
        }
        .add-sub-title {
          font-size: 14px;
          color: #ffffffcc;
        }
      }
      .add-btn {
        width: 95px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background: #76a5ff;
        border-radius: 6px;
        font-size: 14px;
        color: #ffffff;
        cursor: pointer;
        &:hover {
          background: #6390ff;
        }
      }
    }
    .upload-box {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-top: 44px;

      > div {
        display: flex;
        align-items: flex-start;
        .upload-title {
          font-size: 16px;
          color: #333333;
        }
        .juese-item,
        .yinse-item {
          display: flex;
          align-items: center;
          gap: 10px;
          span {
            width: 120px;
            height: 40px;
            background: #eaedf7;
            border-radius: 6px;
            border: 1px solid #d1d6e5;
            line-height: 40px;
            text-align: center;
            font-size: 14px;
            color: #313b5c;
            cursor: pointer;
            box-sizing: border-box;
            .el-icon {
              font-size: 14px;
              color: #7c8aa7;
              margin-left: 8px;
            }
            &:hover {
              color: #0070ff;
              border: 1px solid #0070ff;
              .el-icon {
                color: #0070ff;
              }
            }
          }
        }
        .juese-item {
          display: flex;
          flex-direction: column;
          .man-item {
            display: flex;
            gap: 10px;
            span {
              &.active {
                color: #0070ff;
                border: 1px solid #0070ff;
                .el-icon {
                  color: #0070ff;
                }
              }
            }
          }
          .woman-item {
            display: flex;
            gap: 10px;
            span {
              &.active {
                color: #0070ff;
                border: 1px solid #0070ff;
                .el-icon {
                  color: #0070ff;
                }
              }
            }
          }
        }
        .upload-area {
          margin-left: 20px;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          .upload-img {
            margin-top: 24px;
            width: 240px;
            height: 150px;
            // border: 1px solid #d7d7d7;
            background-color: #fff;
            margin-bottom: 56px;
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
          }
          .upload-audio {
            margin-top: 36px;
          }
        }
      }
    }
    .back-btn {
      position: absolute;
      top: 30px;
      left: 34px;
      width: 86px;
      height: 36px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #a5beff;
      text-align: center;
      font-size: 14px;
      color: #457aff;
      display: flex;
      justify-content: center;
      align-items: center;
      .el-icon {
        font-size: 14px;
        color: #457aff;
        margin-right: 4px;
      }
      cursor: pointer;
    }
    .bottom-btn {
      margin-top: 140px;
    }
  }
}
</style>
